# coding=utf-8

"""
    Created by Kalyter on 2017-11-16.
"""
import csv
import os
import re
from string import punctuation

from learning.util.import_util import import_class

EXTRACT_BODY = re.compile(r'.*<body>(.*)</body>')
TRIM_SYMBOL = re.compile(r'[%s]' % punctuation)
DELETE_NUM = re.compile(r'\d')
DELETE_TAG = re.compile(r'<[^>]+>')
DELETE_NONSENSE = [
    re.compile(r'<chapter name="preamble".*?</chapter>'),
    # re.compile(r'<chapter number="chapter 1".*?</chapter>'),
]
TRIM_LARGE_SPACE = re.compile(r' {2,}')
EXTRACT_TYPE = re.compile(r'.*<type>(.*)</type>')
EXTRACT_LANGUAGE = re.compile(r'.*<language>(.*)</language>')
EXTRACT_NAME = re.compile(r'.*<name>(.*)</name>')
EXTRACT_DATE = re.compile(r'.*<date_into_force>(.*)</date_into_force>')


def extract_info(raw):
    """提取文件基本信息"""
    content_type = EXTRACT_TYPE.match(raw).group(1) if EXTRACT_TYPE.match(raw) else ''
    content_language = EXTRACT_LANGUAGE.match(raw).group(1) if EXTRACT_LANGUAGE.match(raw) else ''
    name = EXTRACT_NAME.match(raw).group(1) if EXTRACT_NAME.match(raw) else ''
    date = EXTRACT_DATE.match(raw).group(1) if EXTRACT_DATE.match(raw) else ''
    return {
        '名称': name,
        '类型': content_type,
        '语言': content_language,
        '日期': date
    }


def process_text(raw):
    """处理文件信息"""

    content = EXTRACT_BODY.match(raw).group(1)
    # 1.全部转换成小写
    # 2.删除所有标点符号
    # 3.删除所有数字
    # 4.删除所有空行，单词间空格不删
    # 5.删除所有高亮标签

    for delete_nonsense in DELETE_NONSENSE:
        content = delete_nonsense.sub('', content)

    content = DELETE_TAG.sub('', content)

    content = TRIM_SYMBOL.sub('', content)

    content = DELETE_NUM.sub('', content)

    content = TRIM_LARGE_SPACE.sub(' ', content)

    return content


def read(filename):
    open_file = open(filename, 'r', encoding='utf-8')
    try:
        raw = open_file.read()
        raw = raw.replace('\n', '').strip()
    finally:
        open_file.close()

    raw = raw.lower()
    info = extract_info(raw)
    content = process_text(raw)

    return info, content


def read_path(path, max_comparision=None):
    file_list = os.listdir(path)
    file_list.sort()
    file_list = file_list[:max_comparision]
    for file in file_list:
        yield os.path.join(path, file)


def read_csv(filename):
    result = []
    with open(filename, encoding='utf-8') as file:
        reader = csv.reader(file)
        for row in reader:
            result.append(row)
    return result


class Reader(object):
    """读取器，可自定义来源位置，来源类型和输出类型等内容。"""

    def __init__(self, fullname):
        self._source = None
        self._type = None
        self._view = None
        self._rows = []
        self._fullname = fullname

    @property
    def nrows(self):
        """返回行数"""
        return len(self._rows)

    @property
    def rows(self):
        return self._rows

    def row_values(self, row):
        """获取对应行的数据"""
        return self._rows[row]

    def load(self, *args, **kwargs):
        """加载读取内容"""
        raise NotImplementedError


class ReaderFactory(object):
    """读取器工厂"""
    def __init__(self, app):
        self.app = app
        self.register_types = {}

    def create(self, fullname, **kwargs):
        """根据文件绝对路径创建对应的读取器。

        :param str fullname: 文件完整绝对路径（包含文件名）
        """

        register = self.app.config.get('READER_TYPES', {})
        self.register_types.update(register)
        filename = os.path.split(fullname)[1]
        file_type = os.path.splitext(filename)[1][1:]
        module = self.register_types.get(file_type, '')
        cls = import_class(module)
        if cls:
            instance = cls(fullname)
            instance.load(**kwargs)
            return instance
        else:
            raise TypeError('%s unresolved file type' % file_type)
